package com.me.study.concurrent.线程通信;

import com.me.common.util.SleepUtil;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 测试：tryLock() 尝试获得锁，true 表示已获得锁
 *
 * @author ME
 * @date 2021/4/27
 */
public class TestReentrantLock {

    private static final ReentrantLock LOCK = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            if (LOCK.tryLock()) {
                System.out.println(Thread.currentThread().getName() + "加锁成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "加锁失败");
            }
            SleepUtil.seconds(500);
        }, "t1").start();
        SleepUtil.ms(100);

        new Thread(() -> {
            LOCK.lock();
            try {
                if (LOCK.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + "加锁成功");
                } else {
                    System.out.println(Thread.currentThread().getName() + "加锁失败");
                }
                SleepUtil.seconds(5);
            } finally {
                LOCK.unlock();
            }
        }, "t2").start();

        new Thread(() -> {
            LOCK.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "加锁成功");
                SleepUtil.seconds(5);
            } finally {
                LOCK.unlock();
            }
        }, "t3").start();
    }

}
